package com.hh.once;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class BlogIndexInitializer implements CommandLineRunner {

    private final RestHighLevelClient elasticsearchClient;

    // 索引名称
    private static final String INDEX_NAME = "blog";

    @Autowired
    public BlogIndexInitializer(RestHighLevelClient elasticsearchClient) {
        this.elasticsearchClient = elasticsearchClient;
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            // 检查索引是否已存在
            if (!indexExists()) {
                // 索引不存在，创建索引
                createBlogIndex();
                System.out.println("Elasticsearch索引 '" + INDEX_NAME + "' 创建成功");
            } else {
                System.out.println("Elasticsearch索引 '" + INDEX_NAME + "' 已存在，无需创建");
            }
        } catch (Exception e) {
            System.err.println("初始化Elasticsearch索引失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 检查索引是否存在
     */
    private boolean indexExists() throws IOException {
        // 使用 indices() 客户端直接检查索引是否存在
        return elasticsearchClient.indices().exists(
                new GetIndexRequest(INDEX_NAME),
                RequestOptions.DEFAULT
        );
    }


    /**
     * 创建blog索引及其映射
     */
    private void createBlogIndex() throws IOException {
        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);

        // 构建映射
        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("properties")

                // content字段
                .startObject("content")
                .field("type", "text")
                .startObject("fields")
                .startObject("keyword")
                .field("type", "keyword")
                .field("ignore_above", 256)
                .endObject()
                .endObject()
                .endObject()

                // createTime字段
                .startObject("createTime")
                .field("type", "date")
                .endObject()

                // id字段
                .startObject("id")
                .field("type", "long")
                .endObject()

                // isDelete字段
                .startObject("isDelete")
                .field("type", "long")
                .endObject()

                // tags字段
                .startObject("tags")
                .field("type", "text")
                .startObject("fields")
                .startObject("keyword")
                .field("type", "keyword")
                .field("ignore_above", 256)
                .endObject()
                .endObject()
                .endObject()

                // title字段
                .startObject("title")
                .field("type", "text")
                .startObject("fields")
                .startObject("keyword")
                .field("type", "keyword")
                .field("ignore_above", 256)
                .endObject()
                .endObject()
                .endObject()

                // updateTime字段
                .startObject("updateTime")
                .field("type", "date")
                .endObject()

                // userId字段
                .startObject("userId")
                .field("type", "long")
                .endObject()
                .endObject()
                .endObject();

        // 设置映射
        request.mapping(mapping.toString());


        // 执行创建索引请求
        elasticsearchClient.indices().create(request, RequestOptions.DEFAULT);
    }
}
